package net.sxnic.workflow.task.dao;

import java.util.List;

import net.sxinfo.core.spring25.HibernateDao;
import net.sxnic.workflow.task.Task;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

/**
 * 
 * Comments: 任务表hibernateDao实现
 * <p>
 * Author：孙宇飞
 * <p>
 * Create Date：2009-10-14
 * <p>
 * 
 * 
 */
@Repository("taskDao")
public class HibernateTaskDao extends HibernateDao<Task, String> implements
		TaskDao {

	@Override
	public List<Task> findByFromNodeAssignee(String entityId, String fromNode,
			String fromAssignee) {
		List<Task> list = find(
				"from Task where pi.entityId = ? and fromNode=? and fromAssignee = ?  and enabled=true ",
				entityId, fromNode, fromAssignee);

		return list;
	}

	/**
	 * 查询指定实体Id，指定节点，指定人员的任务列表
	 * 
	 * @param entityId
	 *            实体Id
	 * @param nodeName
	 *            节点名
	 * @param assignee
	 *            任务承办人
	 * @return 任务列表
	 */
	public List<Task> getTasks(String entityId, String nodeName, String assignee) {
		StringBuilder sb = new StringBuilder();
		sb.append("from Task t where t.pi.entityId = '" + entityId + "' ");

		if (StringUtils.isNotBlank(nodeName)) {
			sb.append(" and t.name = '" + nodeName + "' ");
		}

		if (StringUtils.isNotBlank(assignee)) {
			sb.append(" and t.assignee = '" + assignee + "' ");
		}

		sb.append("and t.enabled=true and t.status<>'canceled'  order by t.name,t.userOrder");

		List<Task> list = find(sb.toString());
		return list;
	}

	/**
	 * 查询第一个任务
	 * 
	 * @param entityId
	 * @return
	 */
	@Override
	public Task findFirstTask(String entitId) {

		try {
			List<Task> list = find(
					"from Task t where t.pi.entityId = ? and t.enabled=true  order by creationDate asc",
					new Object[] { entitId });

			if (list == null || list.size() == 0)
				return null;
			else
				return list.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
